package cn.lyq.card.ui.userinfo

import android.content.Intent
import android.net.Uri
import androidx.lifecycle.Observer
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.src.Status
import cn.lyq.card.manager.UserManager
import cn.lyq.card.ui.result.ResultActivity
import cn.lyq.card.utils.ImageSysUtils
import cn.lyq.card.utils.getVisibility
import cn.lyq.card.utils.loadUrl
import cn.lyq.card.utils.setClick
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UriUtils
import kotlinx.android.synthetic.main.act_user_info.*
import java.io.File

class UserInfoActivity : BaseActivity() {

    companion object {
        private const val KEY_IMAGE = 1000
        private const val KEY_CAPTURE = 1001
    }

    private val mModel by lazy {
        getVM(UserVM::class.java)
    }
    private var imgUrl: String? = null
    private lateinit var targetUri: Uri

    override fun getLayoutId(): Int = R.layout.act_user_info

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_edit_base_info)


        UserManager.instance.value?.let {
            tvMobile.text = it.phone ?: ""
            tvRealName.text = it.trueName ?: ""
            tvID.text = it.idCode
            groupRealName.visibility = getVisibility(
                it.phone == null && it.trueName == null
                        && it.idCode == null && it.idCardStatus != 1
            )

            imgAvatar.loadUrl(it.userIcon)
            etNickname.setText(
                if (it.agentName?.isEmpty() != false) {
                    it.trueName ?: "请设置昵称"
                } else {
                    it.agentName ?: ""
                }
            )
            tvInviteCode.text = it.invitationCode ?: ""
        }
        groupRealName.visibility = getVisibility(UserManager.instance.value == null)
    }

    override fun initListener() {
        super.initListener()
        imgAvatar.setClick {
            startActivityForResult(ImageSysUtils.openAlbum(), KEY_IMAGE)
        }
        tvConfirmChange.setClick {
            edit()
        }
    }

    private fun upload(file: File) {
        mModel.upload(file).observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> showLoading()
                Status.SUCCESS -> {
                    imgUrl = it.requireData().path
                    dismissLoading()
                    ToastUtils.showShort(R.string.str_upload_success)
                }
                Status.ERROR -> {
                    dismissLoading()
                    ToastUtils.showShort(it.message.getMsg())
                }
            }
        })
    }

    private fun edit() {
        val img = imgUrl ?: UserManager.instance.value?.userIcon ?: ""
        val name = etNickname.text.toString().trim()
        if (name.isEmpty()) {
            ToastUtils.showShort(etNickname.hint)
            return
        }
        mModel.edit(img, name).observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> showLoading()
                Status.SUCCESS -> {
                    dismissLoading()
                    UserManager.post(UserManager.instance.value?.apply {
                        agentName = name
                        userIcon = img
                    })
                    ResultActivity.start(this, 0)
                    finish()
                }
                Status.ERROR -> {
                    dismissLoading()
                    ToastUtils.showShort(it.message.getMsg())
                }
            }
        })
    }

    override fun initObserver() {
        super.initObserver()
        PermissionUtils.permission(PermissionConstants.STORAGE)
            .callback(object : PermissionUtils.FullCallback {
                override fun onGranted(permissionsGranted: List<String>) {
                    LogUtils.d(permissionsGranted)
                }

                override fun onDenied(
                    permissionsDeniedForever: List<String>,
                    permissionsDenied: List<String>
                ) {
                    ToastUtils.showShort(R.string.str_permission_denied_to_save_img_tip)
                    LogUtils.d(permissionsDeniedForever, permissionsDenied)
                }
            })
            .request()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == KEY_IMAGE) {
            if (resultCode == RESULT_OK && data != null) {
                targetUri = ImageSysUtils.createFileUri(System.currentTimeMillis().toString(), this)
                data.data?.let {
                    startActivityForResult(ImageSysUtils.clip(it, targetUri), KEY_CAPTURE)
                }
            }
        } else if (requestCode == KEY_CAPTURE) {
            if (resultCode == RESULT_OK) {
                imgAvatar.loadUrl(targetUri)
                upload(UriUtils.uri2File(targetUri))
            }
        }
    }
}
